import type {
  AxiosInstance,
  // AxiosRequestHeaders,
  AxiosResponse,
  InternalAxiosRequestConfig,
  AxiosError
} from 'axios'
import axios from 'axios'
import { config } from './config'
// import { refreshToken } from '@/api/common'

// const storage = useStorages()
// const globalConfig = storage.get('global_config')

const { base_url, request_timeout } = config
console.log(base_url, request_timeout)
// 请求白名单，无须token的接口
// const whiteList: string[] = ['/login', '/refresh-token']

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: base_url, // api 的 base_url
  timeout: request_timeout, // 请求超时时间
  withCredentials: false // 禁用 Cookie 等信息
})

// request拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // config.headers.Authorization = storage.get('access_token')
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// let message = ''
// response 拦截器
service.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    return response.data
  },
  async (error: AxiosError) => {
    const status: number | undefined = error.response?.status
    switch (status) {
      case 401: {
        // message = 'token 失效，请重新登录'
        const cWindow = window.__MICRO_APP_ENVIRONMENT__
          ? window.rawWindow
          : window
        // 重新刷新 token
        /*const rt = storage.get('refresh_token')
        // console.log(rt)
        if (rt === 'undefined' || !rt) {
          cWindow.location.href = globalConfig.UAA_LOGIN_HTML
        }*/
        /*const res = await refreshToken(rt)
        storage.clearAll()
        storage.set('access_token', 'Bearer ' + res.access_token)
        storage.set('refresh_token', res.refresh_token)*/
        cWindow.location.reload()
        break
      }
      case 403:
        // message = '拒绝访问'
        // ElMessage.error(message)
        break
      case 404:
        // message = '请求地址错误'
        // ElMessage.error(message)
        break
      case 500:
        const message = (error.response?.data as any)?.message || '服务器故障'
        window.$message.warning(message, { duration: 5000 })
        break
      default:
      // message = '网络连接故障'
      // ElMessage.error(message)
    }
    return Promise.reject(error)
  }
)

export { service }
